import mongoose from "mongoose"
import bcrypt from "bcryptjs"
const userSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true, // 唯一
  },
  password: {
    type: String,
    required: true
  },
  isAdmin: {
    type: Boolean,
    required: true,
    default: false
  },
}, {
  timestamps: true, // 更新时更新时间
})

/**
 * 密码加密
 * 在保存数据前执行中间件
 */
userSchema.pre('save', async function (next) {
  if(!this.isModified("password")) { // 如果没有修改密码，不需要操作
    next()
  } else {
    const salt = await bcrypt.genSalt(10)
    this.password = await bcrypt.hash(this.password, salt)
  }
})
/**
 * 密码匹配
 * @param {String} enterPsw 输入的密码
 * @returns Boolean
 */
userSchema.methods.matchPassword = async function(enterPsw) {
  return await bcrypt.compare(enterPsw, this.password)
}


const User = mongoose.model("User", userSchema)

export default User